import { getQuestions } from '@/api/exam/question';
import { Questions } from '@/api/question';
import { getCategories } from '@/api/written/categories';
import { questionTypeSelectOption } from '@/contants/table';
import { Input, Select, Table, DatePicker, Button } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import React, { useEffect, useMemo, useState } from 'react';

interface Props {
  setVisible: (visible: boolean) => void;
  setQuestions: (question: Questions[]) => void;
  form: any;
}

const checkoutOptions = [
  {
    label: '3分',
    value: 3
  },
  {
    label: '5分',
    value: 5
  }
];

const actionOptions = [
  {
    label: '10分',
    value: 10
  },
  {
    label: '15分',
    value: 15
  }
];

const tableCloumns = [
  {
    title: '题目',
    width: '250px',
    dataIndex: 'question',
    key: 'question'
  }
];

export default function AddForm({ form, setVisible, setQuestions }: Props) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [inputVal, setInputVal] = useState<string>('');
  const [type, setType] = useState<string>('');
  const [dataSource, setDataSource] = useState<Questions[]>([]);
  const [rules, setRules] = useState<any>({});
  const [categories, setCategories] = useState<any[]>([]);

  const handleChangeSelectRole = (score: any, type: string) => {
    const rolesCopy = Object.assign({}, rules);
    rolesCopy[type] = score;
    setRules(rolesCopy);
  };

  useEffect(() => {
    if (Object.keys(rules).length === 3 && form) {
      form.setFieldsValue({
        rules
      });
    }
  }, [rules]);

  const filterDataSource = useMemo(
    () =>
      dataSource.filter(
        (it: Questions) => (!inputVal || it.question.includes(inputVal)) && (!type || it.type === type)
      ),
    [inputVal, type, dataSource]
  );
  useEffect(() => {
    getQuestions().then((res) => {
      setDataSource(res.data);
    });
    getCategories().then((res) => {
      setCategories(
        res.data.map((it) => ({
          label: it.categoryName,
          value: it.categoryName
        }))
      );
    });
  }, []);

  useEffect(() => {
    if (form && selectedRowKeys.length) {
      form.setFieldsValue({
        paperContent: dataSource.filter((it) => selectedRowKeys.includes(it._id))
      });
    }
  }, [selectedRowKeys]);

  const handleSelectChange = (selectedRowKeys: any[]) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const handleToDetail = () => {
    setVisible(true);
    setQuestions(dataSource?.filter((it) => selectedRowKeys.includes(it._id)));
  };

  return (
    <>
      <FormItem labelCol={{ span: 4 }} label="试卷名称" name="paperName" rules={[{ required: true }]}>
        <Input placeholder="请输入试卷名称" />
      </FormItem>
      <FormItem labelCol={{ span: 4 }} label="分类" name="categories" rules={[{ required: true }]}>
        <Select placeholder="请输入分类" options={categories} />
      </FormItem>
      <FormItem
        labelCol={{ span: 4 }}
        label="分数规则"
        name="rules"
        rules={[{ required: true, message: '请填完整分数规则' }]}
      >
        <div style={{ display: 'flex' }}>
          <Select
            placeholder="单选/多选"
            onChange={(v) => handleChangeSelectRole(v, '单选/多选')}
            options={checkoutOptions}
          />
          <Select placeholder="简答" onChange={(v) => handleChangeSelectRole(v, '简答')} options={actionOptions} />
          <Select placeholder="编程" onChange={(v) => handleChangeSelectRole(v, '编程')} options={actionOptions} />
        </div>
      </FormItem>
      {/* <FormItem labelCol={{ span: 4 }} label="生效时间" name="time" rules={[{ required: true }]}>
        <RangePicker disabledDate={current => current && current < moment().endOf('day')} showTime />
      </FormItem> */}
      <FormItem label="请选择试题" name="paperContent" rules={[{ required: true }]}>
        <Select mode="tags" style={{ display: 'none' }} />
      </FormItem>
      <Table
        rowKey="_id"
        scroll={{ y: '250px' }}
        title={() => (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <Input.Search
                style={{ width: '200px' }}
                placeholder="请输入题目模糊搜索"
                allowClear
                onSearch={(text) => setInputVal(text)}
              />
              <Select
                placeholder="全部题型"
                style={{ width: '120px', marginLeft: '10px' }}
                onChange={(text) => setType(text)}
                allowClear
                options={questionTypeSelectOption}
              />
            </div>
            <div>
              <Button onClick={handleToDetail} disabled={!selectedRowKeys.length}>
                查看试卷
              </Button>
            </div>
          </div>
        )}
        dataSource={filterDataSource}
        columns={tableCloumns}
        rowSelection={{ selectedRowKeys, onChange: handleSelectChange }}
      />
    </>
  );
}
